<template>
  <div class="myContainer" >
    <el-row class="myTitleBorderBottom">
      <el-col :span="12" class="myLineHeight_40px">{{title}}</el-col>
      <el-col :span="12" class="myTextAlignRight">  
        <a id="downlink"></a>                 
        <el-button type="primary" class="myBgGreen" @click="onExport" :loading="loadingExport">导出</el-button>
      </el-col>
    </el-row>
    <el-row class="myMarginTop_10px" :gutter="10">    	
      <el-col :span="3">
        <template>
          <el-select 
            v-model="hierarchyValue"
            @change="changeLevel"
            placeholder="层级">
            <el-option
              v-for="item in hierarchyList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="3">
        <template>
          <el-select
            v-model="regionValue"
            multiple
            collapse-tags
            class="mySelect"
            placeholder="区域">
            <el-option
              v-for="item in regionList"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="4">
        <template>
          <el-select v-model="worklistType" clearable placeholder="全部工单类型">
            <el-option
              v-for="item in worklistOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-col>
      <el-col :span="6">
        <el-date-picker
          v-model="time"
          type="daterange" 
          format="yyyy-MM-dd"
          value-format="yyyy-MM-dd"
          unlink-panels
          :clearable="false"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions">
        </el-date-picker>
      </el-col> 
      <el-col :span="3">
        <el-button type="primary" class="myBgGreen" @click="search">查 询</el-button>
      </el-col>
    </el-row>
   	<el-row class="myMarginTop_10px">
      <el-col :span="24">
        <el-table
          ref="multipleTable"
          :data="list"
          :border = true
          :stripe = true
          v-loading="loading"
          style="width: 100%">
          <el-table-column
            type="index"
            label="序号"
            width="55">
          </el-table-column>
          <!-- <el-table-column
            prop="custArea"
            label="片区名称">
          </el-table-column> -->
          <el-table-column
            prop="custCorpName"
            label="项目名称">
          </el-table-column>
          <!-- <el-table-column
            prop="area_name"
            label="工单类型">
          </el-table-column> -->
          <el-table-column
            prop="_woType"
            label="类别">
          </el-table-column>
          <el-table-column
            prop="_sum"
            label="数量">
          </el-table-column>
        </el-table>

        <div class="block">                    
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="page"
            :page-sizes="[10, 15]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    
  </div>

</template>
<style>
  .mySelect .el-input__inner,.mySelect .el-select__tags{
    height: 40px !important;
    overflow: hidden;
  }
  .mySelect.el-select .el-tag{
    margin: 8px 0 3px 6px !important;
  }
</style>
<style scoped>
  .myContainer{
    background: #fff;
    padding: 10px;
  }
  .myTitleBorderBottom{
    color: #000;
    font-weight: 500;
    font-size: 16px;
    border-bottom: 1px solid #dbdbdb;
  }
  .myBgGreen{
    background: #00c2a9;
    border-color: #00c2a9;
    color: #fff;
    margin-top:2px;
  }
  .myBgGreen:hover{
    background: #33ceba;
  }
  .myTextAlignRight{
    text-align: right;
  }
  .myLineHeight_40px{
    line-height: 40px;
  }
  .myMarginTop_10px{
    margin-top: 10px;
  }
  .myPaddingBottom_10px{
    padding-bottom: 10px;
  }
   .myMarginTop_5px{
    margin-top: 5px;
  }
  .myLeftMsg{
    line-height: 40px;
    text-align: right;
    padding-right: 10px;
  }
</style>

<script>
  import { keyMapping , getRegioninfo } from '@/api/affair_setting';
  import { EXTENSION , PASSWORD , BASE_400 } from '@/config/baseUrl';
  import { getLevelArea } from "@/api/area";
  let XLSX = require('xlsx');
  export default {
    data(){
      return{  
        title:"工单类型类别统计表",
        loadingExport:false,
        limit: 10,  
        page: 1,  
        total:null,  
        hierarchyValue:1,
        hierarchyList:[
          {value:1,label:"集团"},
          {value:2,label:"片区"},
          {value:3,label:"小区"},
        ],
        regionValue:[],
        regionList:[],
        regionOptions: [],
        regionOptSelected: [],
        worklistType:"",
        worklistOptions:[
          {label:"报修类",value:"报修类"},
          {label:"报事类",value:"报事类"},
          {label:"投诉类",value:"投诉类"}
        ],
        time:[],
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一年',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 365);
              picker.$emit('pick', [start, end]);
            }
          }]
        }, 
        list:[],
        custCorpName:"",
        i:0,
        loading:false,
        type:1
      }
    },
    filters: {
       
    },
    computed: { 
    },
    created(){
      this.time=[this.GMTToStr(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7)),this.GMTToStr(new Date())];
    },
    mounted(){
      document.title = this.title;
      this.changeLevel(1);
      this.outFile = document.getElementById('downlink');
    },
    methods:{
      handleSizeChange(val) {
        this.limit = val;
        this.ongetWorkTotal();
      },
      handleCurrentChange(val) {
        this.page = val;
        this.ongetWorkTotal();
      },
      GMTToStr(time){
        let date = new Date(time)
        let Str=date.getFullYear() + '-' +
        (date.getMonth() + 1) + '-' + 
        date.getDate() 
        //+ ' ' + 
        // date.getHours() + ':' + 
        // date.getMinutes() + ':' + 
        // date.getSeconds()
        return Str
      },
      search(){
        let vm=this;
        let params={
          level:vm.hierarchyValue,
          id_list:vm.regionValue.toString()
        }
        getRegioninfo(params).then(response => {
          let res=response.data;
          if(res){
            vm.custCorpName=res.replace(/&/g,'%26');
            vm.ongetWorkTotal();
          }
        }).catch(error => {})
      },
      ongetWorkTotal(){
        let vm=this;
        vm.loading=true;
        vm.$http.get(`${BASE_400}/voip/ext/op/api/getWorkTotal.json?type=${vm.type}&extension=${EXTENSION}&password=${PASSWORD}&startTime=${vm.time[0]} 00:00:00&endTime=${vm.time[1]} 23:59:59&wotName=${vm.worklistType}&custCorpName=${vm.custCorpName}&page=${vm.page}&limit=${vm.limit}&orderField=custCorpName`).then(response => {
          let res=response.data;
          vm.list=res.rows||[];
          vm.limit=res.limit;
          vm.page=res.page;
          vm.total=res.total;
          vm.loading=false;
        }).catch(error => {
          vm.loading=false;
          vm.$message.error("执行失败！");
        })
      },
      changeLevel(val){
        let vm=this;
        let params={
          level:val
        }
        getLevelArea(params).then(response => {
          let res=response.data;
          vm.regionList=res;
          if(res.length>0 && vm.hierarchyValue==1){
            vm.regionValue=[res[0].value];
            if(vm.i==0){
              vm.search();
              vm.i=1;
            }
          }else{
            vm.regionValue=[];
          }
        }).catch(error => {})
      },
      onExport(){
        let vm=this;
        vm.loadingExport=true;
        vm.$http.get(`${BASE_400}/voip/ext/op/api/getWorkTotal.json?type=${vm.type}&extension=${EXTENSION}&password=${PASSWORD}&startTime=${vm.time[0]} 00:00:00&endTime=${vm.time[1]} 23:59:59&wotName=${vm.worklistType}&custCorpName=${vm.custCorpName}&page=1&limit=${vm.total}&orderField=custCorpName`).then(response => {
          let res=response.data.rows;
          // let res=vm.list;
          if(res.length==0){
            vm.loadingExport=false;
            vm.$message.info("没有可导出的数据！");
            return;
          }
          for(let i=0; i<res.length; i++){
            delete res[i]['custArea'];
          }
          let data = [{}],name="类型类别统计表"+vm.time[0]+'至'+vm.time[1];
          for (let k in res[0]) {
            data[0][k] = k
          }
          data = data.concat(res);
          vm.downloadExl(data, name);
          vm.loadingExport=false;
          vm.$message.success(`导出成功！总共${res.length}条数据。`);
        }).catch(error => {
          vm.loadingExport=false;
          vm.$message.error("导出失败！");
        })
      },
      downloadExl: function (json, downName, type) {  // 导出到excel
        let keyMap = []
        for (let k in json[0]) {
          keyMap.push(k);
        }
        let tmpdata = [] 
        json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
          v: v[k],
          position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
        }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
          tmpdata[v.position] = {
            v: keyMapping[v.v] || v.v
          }
        })
        let outputPos = Object.keys(tmpdata)  
        let tmpWB = {
          SheetNames: ['类型类别统计表'], 
          Sheets: {
            '类型类别统计表': Object.assign({},
              tmpdata, 
              {
                '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] 
              })
          }
        }
        let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
          {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} 
        ))], {
          type: ''
        }) 
        var href = URL.createObjectURL(tmpDown)  
        this.outFile.download = downName + '.xlsx'  
        this.outFile.href = href  
        this.outFile.click()  

        setTimeout(function () {  
          URL.revokeObjectURL(tmpDown) 
        }, 100)
      },
      s2ab: function (s) { 
        var buf = new ArrayBuffer(s.length)
        var view = new Uint8Array(buf)
        for (var i = 0; i !== s.length; ++i) {
          view[i] = s.charCodeAt(i) & 0xFF
        }
        return buf
      },
      getCharCol: function (n) { 
        let s = ''
        let m = 0
        while (n > 0) {
          m = n % 26 + 1
          s = String.fromCharCode(m + 64) + s
          n = (n - m) / 26
        }
        return s
      }
     
    }

  }


</script>

